#### Figure S5: Pooled Norm violation support (continuous DV) ####

# Libraries
# library(here)
# library(rio)
# library(tidyverse)
# library(ggthemes)
# library(srvyr)

# data_pnas = import(here("Data","data_pnas.rds"))
# source(here("Code","Functions","funcs_theme.R"))

violence_ind_c = paste0("violence",1:6,"c")
norm_ind_c = paste0("norm_",c("judges","polling","censorship","loyalty"),"c")

cs_summary_agg_c = data_pnas |> 
  select(all_of(c(violence_ind_c, norm_ind_c)),
         uid, weight) |> 
  pivot_longer(-c("uid","weight"), names_to = "var", values_to = "val") |> 
  as_survey_design(ids = uid, weights = weight) |> 
  group_by(var) |> 
  summarise(val_sum = survey_mean(val, na.rm = T, vartype = "ci")) |> 
  ungroup() 

cs_summary_agg_c<- cs_summary_agg_c |> filter(var != "violence1c") |>
  filter(var != "violence2c") 

cs_summary_agg_c<- cs_summary_agg_c |>  mutate(var_typ = ifelse(str_detect(var,"norm"), "Democratic Norms", "Violence"),
                                               var = recode_factor(var,
                                                                   norm_pollingc = "Reduce outparty polling stations",
                                                                   norm_loyaltyc = "More loyal to party than Constitution\nin contested elections",
                                                                   norm_judgesc = "Ignore outparty court decisions",
                                                                   norm_executivec = "President should circumvent Congress",
                                                                   norm_censorshipc = "Censor partisan media",
                                                                   violence6c = "Murder",
                                                                   violence5c = "Assault with deadly weapon",
                                                                   violence4c = "Arson",
                                                                   violence3c = "Assault",
                                                                   violence2c = "Vandalism",
                                                                   violence1c = "Protest without permit")
) |> 
  filter(var_typ != "Violence")

fig_s5 = cs_summary_agg_c |> 
  ggplot(aes(x = val_sum, y = tidytext::reorder_within(var, val_sum,var_typ), 
             label = round(val_sum,2))) +
  geom_pointrange(aes(xmin = val_sum_low,
                      xmax = val_sum_upp)) +
  geom_text(aes(x = val_sum + .4)) +
  force_panelsizes(rows = c( 1,.85)) +
  scale_x_continuous(limits = c(1,5)) +
  tidytext::scale_y_reordered() +
  labs(x = "Average Support (1-5)",
       y = NULL) +
  theme_prl()

print(fig_s5)

ggsave(here("Plots","Supplementary","figure_s5.png"),
       fig_s5,
       units = "in",
       width = 5, height = 3.5,
       dpi = 600)